import httpRequest from "..";
import { MyAxiosError, MyAxiosRequestConfig } from "./request";

const MAX_RETRY_COUNT = 3;
const DELAY_TIME = 2000;

let currentCount = 1;
/**
 * 请求重试
 * @param err 错误对象
 * @returns 重试机会用完抛出错误，重试成功则返回请求结果
 */
export async function retryRequest(err: MyAxiosError) {
    if (err.config.retry === false) throw err;
    if (err.message === "canceled") throw err; // 过滤手动取消请求的情况

    const config = err.config as MyAxiosRequestConfig;

    if (MAX_RETRY_COUNT >= currentCount && config) {
        console.log(`重试${currentCount}次...`);
        currentCount++;
        await sleep(DELAY_TIME);
        const res = await httpRequest.getInstance().request({ ...config });
        return Promise.resolve(res);
    }
    console.log("重试次数已用完...");
    currentCount = 0;
    throw err;
}

/**
 * 延迟后续代码执行的工具函数，以同步代码阻塞的方式实现延迟：await sleep()
 * @param delayTime 延迟时间
 * @returns Promise
 */
export function sleep(delayTime: number = 1000) {
    return new Promise(resolve => setTimeout(resolve, delayTime));
}
